package com.xsr.controller;

import com.xsr.utils.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

/**
 * @author 邢式瑞
 * @version 1.0
 * @project springMvcday03
 * @date 2022/9/15 10:08
 */
@Controller
public class LoginController {
    @RequestMapping("/doLogin1")
    public  String dologin1(String username, String password, Model model,Boolean rememberMe){
        System.out.println("记住我"+rememberMe);
        try {
            password= new Md5Hash(password,"xsr",1024).toString();
           // System.out.println(password);
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password.toCharArray());
            if(null != rememberMe){
                //记住我
                usernamePasswordToken.setRememberMe(rememberMe.booleanValue());
            }
            Subject subject = SecurityUtils.getSubject();
            subject.login(usernamePasswordToken);
        } catch (AuthenticationException e) {

            model.addAttribute("error",e);
            return "/login.jsp";

        }
        return "redirect:/index.jsp";
    }

    @RequestMapping("/logout")
    @ResponseBody
    public Result logout(Map map){
        //1.得到subject
        Subject subject = SecurityUtils.getSubject();
        //2.退出
        map.put("code","0");
        subject.logout();

        return Result.ok("退出成功");

    }

}


